﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SingletonDemo
{
    public class Singleton4
    {
        private static Singleton4 instance = null;

        private Singleton4()
        {

        }

        public static Singleton4 GetInstance()
        {
            if (instance == null)
            {
                instance = new Singleton4();
            }
            return instance;
        }

        public void Test1(string name)
        {
            Console.WriteLine("Singleton3 operation" + name);
        }

        public string Test2()
        {
            Console.WriteLine("Singleton3 notify");
            return "你好 怡宝";
        }
    }
    public class Singleton41
    {
        //饿汉模式
        private static Singleton41 instance = new Singleton41();

        private Singleton41()
        {

        }

        public static Singleton41 GetInstance()
        {
            return instance;
        }

        public void Test1(string name)
        {
            Console.WriteLine("Singleton3 operation" + name);
        }

        public string Test2()
        {
            Console.WriteLine("Singleton3 notify");
            return "你好 怡宝";
        }
    }

    public class Singleton42
    {
        private static Singleton42 instance = null;

        private Singleton42()
        {

        }

        private static object obj = new object();
        public static Singleton42 GetInstance()
        {
            //懒汉模式
            if (instance == null)
            {
                lock(obj)
                {
                    if (instance == null)
                    {
                        instance = new Singleton42();
                    }
                }
            }
            return instance;
        }

        public void Test1(string name)
        {
            Console.WriteLine("Singleton3 operation" + name);
        }

        public string Test2()
        {
            Console.WriteLine("Singleton3 notify");
            return "你好 怡宝";
        }
    }
}
